﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class MyCompanies : System.Web.UI.Page
{
    List<_User_company> User_company;
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
    int UserID;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.IsAuthenticated == false)
        {
            Response.Redirect("login.aspx");
        }

        if (Request.IsAuthenticated)
        {
            string n = "";
            UserID = Convert.ToInt32(User.Identity.Name);
            SqlCommand sCmd = new SqlCommand("SELECT name FROM USERS WHERE id=@id", conn);
            sCmd.Parameters.Add(new SqlParameter("@id", SqlDbType.Int)).Value = User.Identity.Name;
            conn.Open();
            SqlDataReader dr = sCmd.ExecuteReader();
            while (dr.Read())
            {
                string name = Convert.ToString(dr[0].ToString());
                n = name;
            }
            dr.Close();
            conn.Close();           

            WelcomeBackMessage.Text = "Welcome back, " + n + "!";

            AuthenticatedHeaderPanel.Visible = true;
            AuthenticatedMessagePanel.Visible = true;
            AuthenticatedMenuPanel.Visible = true;

            if (!IsPostBack)
            {
                SetData();
            }
        }
        else
        {
            AuthenticatedHeaderPanel.Visible = false;
            AuthenticatedMessagePanel.Visible = false;
            AuthenticatedMenuPanel.Visible = false;
        }

    }

    private void SetData()
    {
        User_company = _User_company.Select_User_company(User.Identity.Name);
        if (User_company.Count == 0)
        {
            message_no_companies.Visible = true;
            bt_delete.Visible = false;
        }
        else
        {
            message_no_companies.Visible = false;
            Company_list.DataSource = User_company;
            Company_list.DataBind();
            bt_delete.Visible = true;
            foreach (ListViewItem item in Company_list.Items)
            {
                Label deleted = (Label)item.FindControl("statusLabel");
                if (deleted.Text == "Deleted")
                {
                    ImageButton edit = (ImageButton)item.FindControl("lnkEdit");
                    ImageButton delete = (ImageButton)item.FindControl("lnkDelete");
                    CheckBox cb = (CheckBox)item.FindControl("cb_delete_companies");
                    edit.Enabled = false;
                    delete.Enabled = false;
                    cb.Enabled = false;
                }
            }
        }
    }

    protected void Company_list_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        if (e.CommandName == "Company")
        {
            var id_company = e.Item.FindControl("id_companyLabel") as Label;
            Session["Company_ID"] = id_company.Text;
        }
        if (e.CommandName == "Edit")
        {
            var id_user_company = e.Item.FindControl("id_user_companyLabel") as Label;
            var id_company = e.Item.FindControl("id_companyLabel") as Label;
            Session["User_Company_ID"] = id_user_company.Text;
            Session["Company_ID"] = id_company.Text;
            Edit_Company(id_company.Text, id_user_company.Text);            
        }
        if (e.CommandName == "Delete")
        {
            var id_company = e.Item.FindControl("id_companyLabel") as Label;
            lbl_CompanyID.Text = id_company.Text;
            lbl_selected_companies.Text = "";
            Modal_Popup_Delete.Show();
        }
    }
    protected void Company_list_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
    {
        DataPager Company_list_Page = (Company_list.FindControl("Company_list_Page")) as DataPager;
        Company_list_Page.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
        SetData();
    }
    protected void Company_list_Editing(object sender, ListViewEditEventArgs e)
    {

    }
    protected void Company_list_ItemDeleting(object sender, ListViewDeleteEventArgs e)
    {

    }    

    //Kompāniju dzēšana POPUP
    protected void bt_delete_company_Click(object sender, EventArgs e)
    {
        if (lbl_selected_companies.Text == "True")
        {
            Select_to_delete_companies();
            foreach (string companieID in selected_companyID)
            {
                //Katrai ieķeksētajai kompānijai nomaina statusu uz DELETED
                _User_company.Delete(companieID);
                SetData();
            }
        }
        else
        {
            _User_company.Delete(lbl_CompanyID.Text);
            SetData();
        }
    }
    protected void bt_delete_cancel_Click(object sender, EventArgs e)
    {
        Modal_Popup_Delete.Hide();
    }

    //Vairāku kompāniju dzēšana
    List<string> selected_companyID = new List<string>();
    protected void bt_delete_companies_Click(object sender, EventArgs e)
    {
        Select_to_delete_companies();
        if (selected_companyID.Count == 0)
        {
            Page.ClientScript.RegisterStartupScript(typeof(Page), "myalert", "alert('Select companies to delete!');", true);
        }
        else
        {
            lbl_selected_companies.Text = "True";
            Modal_Popup_Delete.Show();
        }
    }
    public void Select_to_delete_companies()
    {
        foreach (ListViewItem item in Company_list.Items)
        {
            CheckBox cb_delete_companies = (CheckBox)item.FindControl("cb_delete_companies");
            if (cb_delete_companies.Checked)
            {
                Label id_companie = (Label)item.FindControl("id_companyLabel");
                string companie_id = id_companie.Text;
                //ieķeksētās kompānijas ID ieliek listā
                selected_companyID.Add(companie_id);
            }
        }
    }

    protected void bt_add_new_company_Click(object sender, EventArgs e)
    {
        Add_Company(User.Identity.Name);
        Modal_add_company.Show();
    }
    protected void bt_cancel_Click(object sender, EventArgs e)
    {
        Modal_add_company.Hide();
    }
    
    //Kompāniju Pievienošana/Labošana POPUP
    #region Add/Edit Companie POPUP
    public void Fill_Bank_cbo()
    {
        Drop_bank.Items.Clear();
        SqlCommand selCmd = new SqlCommand("SELECT id, bank_name FROM bank", conn);
        conn.Open();
        SqlDataReader dr = selCmd.ExecuteReader();
        while (dr.Read())
        {
            ListItem item = new ListItem();
            item.Value = dr["id"].ToString();
            item.Text = dr["bank_name"].ToString();
            Drop_bank.Items.Add(item);
        }
        Drop_bank.Items.Insert(0, "--Select--");
        dr.Close();
        conn.Close();
    }    

    public void Add_Company(string user_id)
    {
        lit_add_company.Text = "Add new company!";
        lbl_company_id.Text = "";
        lbl_user_company_id.Text = "";
        lbl_edit_company.Text = "";
        modal_message_company.Text = "&nbsp";
        modal_message_bank.Text = "&nbsp";
        modal_message_address.Text = "&nbsp";
        if (lbl_company_id.Text == "" && lbl_user_company_id.Text == "")
        {
            tb_comp_name.Text = "";
            tb_comp_reg_nr.Text = "";
            lbl_comp_vat.Text = "";
            cb_main_comp.Checked = false;
            tb_position.Text = "";
            lbl_user_id.Text = user_id;
            Bank_list.DataSource = Company_bank;
            Bank_list.DataBind();
            Address_list.DataSource = Company_address;
            Address_list.DataBind();
            Fill_Bank_cbo();            
            lbl_user.Text = _User.EditUser(UserID)._Name + " " + _User.EditUser(UserID)._SecondName;
            tab_company_banks.Enabled = false;
            tab_company_address.Enabled = false;
        }
    }
    public void Edit_Company(string id_company, string id_user_company)
    {
        modal_message_company.Text = "&nbsp";
        modal_message_bank.Text = "&nbsp";
        modal_message_address.Text = "&nbsp";
        lit_add_company.Text = "Edit company!";
        tab_company_address.Enabled = true;
        tab_company_banks.Enabled = true;

        lbl_edit_company.Text = "Edit";
        lbl_company_id.Text = id_company;
        lbl_user_company_id.Text = id_user_company;
        lbl_user_id.Text = User.Identity.Name;

        lbl_user.Text = _User.EditUser(UserID)._Name + " " + _User.EditUser(UserID)._SecondName;

        lbl_user_company_id.Text = Convert.ToString(_User_company.Sel_User_company(lbl_company_id.Text)._id_user_company);
        lbl_company_id.Text = Convert.ToString(_User_company.Sel_User_company(lbl_company_id.Text)._id_company);

        tb_comp_name.Text = _User_company.Sel_User_company(lbl_company_id.Text)._company_name;
        tb_comp_reg_nr.Text = _User_company.Sel_User_company(lbl_company_id.Text)._company_reg_nr;
        lbl_comp_vat.Text = _User_company.Sel_User_company(lbl_company_id.Text)._company_vat;

        cb_main_comp.Checked = _User_company.Sel_User_company(lbl_company_id.Text)._main_company;
        tb_position.Text = _User_company.Sel_User_company(lbl_company_id.Text)._position;
        Fill_Bank_cbo();
        SetData_Address_Bank();
    }  
    
    //POPUP poga
    protected void bt_add_company_Click(object sender, EventArgs e)
    {
        string user_company = lbl_user_company_id.Text;
        string company_id = lbl_company_id.Text;
        string id_user = lbl_user_id.Text;
        string comp_name = tb_comp_name.Text;
        string comp_reg_nr = tb_comp_reg_nr.Text;
        string comp_vat = "LV" + tb_comp_reg_nr.Text;
        string main_comp = cb_main_comp.Checked.ToString();
        string position = tb_position.Text;
        string client = "false";
        string status = "Active";

        if (lbl_edit_company.Text == "Edit")
        {
            try
            {
                _User_company.Update(user_company, id_user, company_id, main_comp, position, comp_name, comp_reg_nr, comp_vat, client, status);
                if (modal_message_company.ForeColor != System.Drawing.Color.Green)
                {
                    modal_message_company.Text = "Saved!";
                    modal_message_company.ForeColor = System.Drawing.Color.Green;
                }
            }
            catch
            {
                if (modal_message_company.ForeColor != System.Drawing.Color.Red)
                {
                    modal_message_company.Text = "Error saving data!";
                    modal_message_company.ForeColor = System.Drawing.Color.Red;
                }
            }
        }
        else
        {
            try
            {
                _User_company.Insert_Company(comp_name, comp_reg_nr, comp_vat, id_user, main_comp, position, client);

                SqlCommand sCmd_MAX_user_company_id = new SqlCommand("SELECT MAX(id) FROM user_company WHERE id_user=@user_id AND client=@clientt", conn);
                sCmd_MAX_user_company_id.Parameters.Add(new SqlParameter("@user_id", System.Data.SqlDbType.Int)).Value = id_user;
                sCmd_MAX_user_company_id.Parameters.Add(new SqlParameter("@clientt", System.Data.SqlDbType.NVarChar)).Value = "false";
                conn.Open();
                lbl_user_company_id.Text = Convert.ToString(sCmd_MAX_user_company_id.ExecuteScalar());
                conn.Close();
                
                SqlCommand sCmd_MAX_comp = new SqlCommand("SELECT id_company FROM user_company WHERE id=@id AND client=@clientt", conn);
                sCmd_MAX_comp.Parameters.Add(new SqlParameter("@id", System.Data.SqlDbType.Int)).Value = lbl_user_company_id.Text;
                sCmd_MAX_comp.Parameters.Add(new SqlParameter("@clientt", System.Data.SqlDbType.NVarChar)).Value = "false";
                conn.Open();
                lbl_company_id.Text = Convert.ToString(sCmd_MAX_comp.ExecuteScalar());
                conn.Close();

                Edit_Company(lbl_company_id.Text, lbl_user_company_id.Text);

                if (modal_message_company.ForeColor != System.Drawing.Color.Green)
                {
                    modal_message_company.Text = "Saved!";
                    modal_message_company.ForeColor = System.Drawing.Color.Green;
                }
            }
            catch
            {
                if (modal_message_company.ForeColor != System.Drawing.Color.Red)
                {
                    modal_message_company.Text = "Error saving data!";
                    modal_message_company.ForeColor = System.Drawing.Color.Red;
                }
            }
        }        
    }

    List<_Company_bank> Company_bank;
    List<_Adress> Company_address;
    public void SetData_Address_Bank()
    {
        if (lbl_company_id.Text != "")
        {
            Company_bank = _Company_bank.Select_Company_bank(lbl_company_id.Text);
            Company_address = _Adress.Select_Company_address(lbl_company_id.Text);

            if (Company_bank.Count == 0)
            {

                message_no_bank.Visible = true;
                Bank_list.DataSource = Company_bank;
                Bank_list.DataBind(); 
            }
            else
            {
                message_no_bank.Visible = false;
                lbl_account_id.Text = "";
                lbl_company_bank_id.Text = "";
                lbl_bank_id.Text = "";
                lbl_edit_bank.Text = "";
                bt_ok_bank.Text = "Add";
                tb_account.Text = "";                
                Fill_Bank_cbo();
                Bank_list.DataSource = Company_bank;
                Bank_list.DataBind();                
            }
            if (Company_address.Count == 0)
            {
                message_no_addresses.Visible = true;
                lbl_edit_address.Text = "";
                Address_list.DataSource = Company_address;
                Address_list.DataBind();
            }
            else
            {
                message_no_addresses.Visible = false;
                lbl_address_id.Text = "";
                lbl_edit_address.Text = "";
                bt_ok_address.Text = "Add";
                tb_address.Text = "";
                Address_list.DataSource = Company_address;
                Address_list.DataBind();
            }
            Modal_add_company.Show();
        }
    }

    protected void Bank_list_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
    {
        DataPager Bank_list_Page = (Bank_list.FindControl("Bank_list_Page")) as DataPager;
        Bank_list_Page.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
        SetData_Address_Bank();
    }
    protected void Bank_list_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        if (e.CommandName == "Edit")
        {
            lbl_edit_bank.Text = "Edit";
            tb_account.Text = "";
            bt_ok_bank.Text = "Edit";
            modal_message_bank.Text = "";

            var company_bank_ID = e.Item.FindControl("id_company_bankLabel") as Label;
            lbl_company_bank_id.Text = company_bank_ID.Text;
            
            var bank_ID = e.Item.FindControl("id_bankLabel") as Label;
            lbl_bank_id.Text = bank_ID.Text;

            var account_ID = e.Item.FindControl("id_accountLabel") as Label;
            lbl_account_id.Text = account_ID.Text;

            try
            {
                Drop_bank.SelectedValue = _Company_bank.Select(lbl_company_bank_id.Text)._id_bank.ToString();
                tb_account.Text = _Company_bank.Select(lbl_company_bank_id.Text)._account.ToString();                
            }
            catch
            {
                if (modal_message_bank.ForeColor != System.Drawing.Color.Red)
                {
                    modal_message_bank.Text = "Error selecting data!";
                    modal_message_bank.ForeColor = System.Drawing.Color.Red;
                }
            }
        }

        if (e.CommandName == "Delete")
        {
            try
            {
                var company_bank_ID = e.Item.FindControl("id_company_bankLabel") as Label;
                _Company_bank.Delete(company_bank_ID.Text);
                if (modal_message_bank.ForeColor != System.Drawing.Color.Green || modal_message_bank.ForeColor == System.Drawing.Color.Green)
                {
                    modal_message_bank.Text = "Deleted!";
                    modal_message_bank.ForeColor = System.Drawing.Color.Green;
                }
                SetData_Address_Bank();
            }
            catch
            {
                if (modal_message_bank.ForeColor != System.Drawing.Color.Red)
                {
                    modal_message_bank.Text = "Error deleting data!";
                    modal_message_bank.ForeColor = System.Drawing.Color.Red;
                }
            }
        }
    }
    //Ķipa Bankas dzēšanas jQuery dialogboxis bet kārtīgi nestrādā(confirmValue- neattīrās) Ja izdomā kā attīrīt tad pie pogas jāpievieno: OnClick = "OnBankConfirm" OnClientClick = "Confirm()"
    public void OnBankConfirm(object sender, EventArgs e)
    {
        string confirmValue = Request.Form["confirm_value"];
        if (confirmValue == "Yes")
        {
            SetData_Address_Bank();
        }
        else if (confirmValue == "No")
        {
            SetData_Address_Bank();
        }
    }
    protected void Bank_list_ItemEditing(object sender, ListViewEditEventArgs e)
    {

    }
    protected void Bank_list_ItemDelete(object sender, ListViewDeleteEventArgs e)
    {

    }
    protected void bt_ok_bank_Click(object sender, EventArgs e)
    {
        string bank_id = Drop_bank.SelectedItem.Value;

        if (lbl_edit_bank.Text == "")
        {
            try
            {
                _Company_bank.Insert(lbl_company_id.Text, bank_id, tb_account.Text);
                if (modal_message_bank.ForeColor != System.Drawing.Color.Green || modal_message_bank.ForeColor == System.Drawing.Color.Green)
                {
                    modal_message_bank.Text = "Saved!";
                    modal_message_bank.ForeColor = System.Drawing.Color.Green;
                }
            }
            catch
            {
                if (modal_message_bank.ForeColor != System.Drawing.Color.Red)
                {
                    modal_message_bank.Text = "Error saving data!";
                    modal_message_bank.ForeColor = System.Drawing.Color.Red;
                }
            }
        }
        else
        {
            try
            {
                _Company_bank.Update(lbl_company_bank_id.Text, lbl_company_id.Text, bank_id, lbl_account_id.Text, tb_account.Text);
                if (modal_message_bank.ForeColor != System.Drawing.Color.Green || modal_message_bank.ForeColor == System.Drawing.Color.Green)
                {
                    modal_message_bank.Text = "Saved!";
                    modal_message_bank.ForeColor = System.Drawing.Color.Green;
                }
            }
            catch
            {
                if (modal_message_bank.ForeColor != System.Drawing.Color.Red)
                {
                    modal_message_bank.Text = "Error saving data!";
                    modal_message_bank.ForeColor = System.Drawing.Color.Red;
                }
            }
        }
        SetData_Address_Bank();
    }
    protected void bt_cancel_bank_Click(object sender, EventArgs e)
    {
        tb_account.Text = "";
        Fill_Bank_cbo();
        lbl_account_id.Text = "";
        lbl_company_bank_id.Text = "";
        lbl_bank_id.Text = "";
        lbl_edit_bank.Text = "";
        bt_ok_bank.Text = "Add";
        modal_message_bank.Text = "&nbsp";
        SetData_Address_Bank();
    }

    protected void Address_list_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
    {
        DataPager Address_list_Page = (Address_list.FindControl("Address_list_Page")) as DataPager;
        Address_list_Page.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
        SetData_Address_Bank();
    }
    protected void Address_list_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        if (e.CommandName == "Edit")
        {
            lbl_edit_address.Text = "Edit";
            tb_address.Text = " ";
            modal_message_address.Text = "&nbsp";
            bt_ok_address.Text = "Edit";

            var addres_ID = e.Item.FindControl("id_addressLabel") as Label;
            int address_id = Convert.ToInt32(addres_ID.Text);
            lbl_address_id.Text = addres_ID.Text;
            try
            {
                tb_address.Text = _Adress.Select(addres_ID.Text)._address.ToString();
            }
            catch
            {
                if (modal_message_address.ForeColor != System.Drawing.Color.Red)
                {
                    modal_message_address.Text = "Error selecting data!";
                    modal_message_address.ForeColor = System.Drawing.Color.Red;
                }
            }
        }
        if (e.CommandName == "Delete")
        {
            try
            {
                var addres_ID = e.Item.FindControl("id_addressLabel") as Label;
                _Adress.Delete(addres_ID.Text);
                if (modal_message_address.ForeColor != System.Drawing.Color.Green || modal_message_address.ForeColor == System.Drawing.Color.Green)
                {
                    modal_message_address.Text = "Deleted!";
                    modal_message_address.ForeColor = System.Drawing.Color.Green;
                }
                SetData_Address_Bank();
            }
            catch
            {
                if (modal_message_address.ForeColor != System.Drawing.Color.Red)
                {
                    modal_message_address.Text = "Error deleting data!";
                    modal_message_address.ForeColor = System.Drawing.Color.Red;
                }
            }
        }
    }
    //Ķipa Adreses dzēšanas jQuery dialogboxis bet kārtīgi nestrādā(confirmValue- neattīrās) Ja izdomā kā attīrīt tad pie pogas jāpievieno: OnClick = "OnAddressConfirm" OnClientClick = "Confirm()"
    public void OnAddressConfirm(object sender, EventArgs e)
    {
        string confirmValue = Request.Form["confirm_value"];
        if (confirmValue == "Yes")
        {
            foreach (ListViewItem item in Address_list.Items)
            {
                SetData_Address_Bank();
            }
        }
        else if (confirmValue == "No")
        {
            SetData_Address_Bank();
        }
       
    }
    protected void Address_list_ItemEditing(object sender, ListViewEditEventArgs e)
    {

    }
    protected void Address_list_ItemDeleting(object sender, ListViewDeleteEventArgs e)
    {

    }
    protected void bt_ok_address_Click(object sender, EventArgs e)
    {
        string id_company = lbl_company_id.Text;
        string id_address = lbl_address_id.Text;

        if (lbl_edit_address.Text == "")
        {
            try
            {
                _Adress.Insert(id_company, tb_address.Text);
                if (modal_message_address.ForeColor != System.Drawing.Color.Green || modal_message_address.ForeColor == System.Drawing.Color.Green)
                {
                    modal_message_address.Text = "Saved!";
                    modal_message_address.ForeColor = System.Drawing.Color.Green;
                }
            }
            catch
            {
                if (modal_message_address.ForeColor != System.Drawing.Color.Red)
                {
                    modal_message_address.Text = "Error saving data!";
                    modal_message_address.ForeColor = System.Drawing.Color.Red;
                }
            }
        }
        else
        {
            try
            {
                _Adress.Update(id_address, id_company, tb_address.Text);
                if (modal_message_address.ForeColor != System.Drawing.Color.Green || modal_message_address.ForeColor == System.Drawing.Color.Green)
                {
                    modal_message_address.Text = "Saved!";
                    modal_message_address.ForeColor = System.Drawing.Color.Green;
                }
            }
            catch
            {
                if (modal_message_address.ForeColor != System.Drawing.Color.Red)
                {
                    modal_message_address.Text = "Error saving data!";
                    modal_message_address.ForeColor = System.Drawing.Color.Red;
                }
            }
        }
        SetData_Address_Bank();
    }
    protected void bt_cancel_address_Click(object sender, EventArgs e)
    {
        tb_address.Text = "";
        lbl_address_id.Text = "";
        lbl_edit_address.Text = "";
        modal_message_address.Text = "&nbsp";
        bt_ok_address.Text = "Add";
        SetData_Address_Bank();
    }

    #endregion
}